import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Typography, message, Spin } from 'antd';
import { ArrowLeftOutlined, MessageOutlined, DeleteOutlined } from '@ant-design/icons';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { getMessageDetail, markMessageRead, deleteMessage } from '../../api/message';
import { PrivateMessage } from '../../types';
import { formatDateTime } from '../../utils/format';
import { useMessage } from '../../context/MessageContext';

const { Title, Text, Paragraph } = Typography;

const MessageDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [messageDetail, setMessageDetail] = useState<PrivateMessage | null>(null);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const { decreaseUnreadCount } = useMessage();

  useEffect(() => {
    if (id) {
      fetchMessageDetail();
    }
  }, [id]);

  const fetchMessageDetail = async () => {
    try {
      setLoading(true);
      const response = await getMessageDetail(Number(id));
      if (response.code === 200) {
        setMessageDetail(response.data);
        // 如果是未读消息，标记为已读
        if (!response.data.isRead) {
          await markMessageRead(response.data.id);
          decreaseUnreadCount(1);
        }
      } else {
        message.error('消息不存在');
        navigate('/messages');
      }
    } catch (error) {
      console.error('获取消息详情失败:', error);
      message.error('获取消息详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!messageDetail) return;
    
    try {
      await deleteMessage(messageDetail.id);
      message.success('删除成功');
      navigate('/messages');
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!messageDetail) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text type="secondary">消息不存在</Text>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Card
        title={
          <Space>
            <MessageOutlined />
            <Title level={3} style={{ margin: 0 }}>
              {messageDetail.subject}
            </Title>
          </Space>
        }
        extra={
          <Space>
            <Button
              type="text"
              icon={<MessageOutlined />}
              onClick={() => navigate(`/messages/compose?reply=${messageDetail.id}`)}
            >
              回复
            </Button>
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              onClick={handleDelete}
            >
              删除
            </Button>
            <Link to="/messages">
              <Button icon={<ArrowLeftOutlined />}>返回</Button>
            </Link>
          </Space>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Space direction="vertical" size="small">
            <div>
              <Text strong>发件人：</Text>
              <Text>{messageDetail.senderUsername}</Text>
            </div>
            <div>
              <Text strong>发送时间：</Text>
              <Text type="secondary">
                {formatDateTime(messageDetail.createdTime || messageDetail.sentTime || '')}
              </Text>
            </div>
          </Space>
        </div>

        <div style={{ 
          borderTop: '1px solid #f0f0f0', 
          paddingTop: 16,
          marginTop: 16 
        }}>
          <Paragraph style={{ whiteSpace: 'pre-wrap', fontSize: '14px' }}>
            {messageDetail.content}
          </Paragraph>
        </div>
      </Card>
    </div>
  );
};

export default MessageDetail; 